const util = require('../../utils/util.js')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    API_BASE_URL: util.API_BASE_URL,
    type: '',
    typeIndex: 1,
    dayIndex: 0,
    billid: '', //行程单id
    progressList: [],
    recordList: [],
    targetId: '',
    offsets: [0]      // 元素顶部位置数组
  },
  //派单
  paidan() {
    const { pdgl_order_id, pdgl_pk_billtype, pdgl_process_id, pdgl_pk,pdgl_task_id } = this.data.hpXcdVOS;
    util.request(util.API_BASE_APP_URL+'itf/common/hongpei/getToken.json', {
      'X-EOA-TOKEN': wx.getStorageSync('X-EOA-TOKEN') || ''
    }).then(res => {
      if (res.success) {
        let url = `/pages/pdWebView/pdWebView`;
        url += `?orderId=${pdgl_order_id}`;
        url += `&taskId=${pdgl_task_id}`;
        url += `&processId=${pdgl_process_id}`;
        url += `&pk_billtype=${pdgl_pk_billtype}`;
        url += `&billid=${pdgl_pk}`;
        url += `&X-EOA-TOKEN=${res.data}`;
        wx.navigateTo({
          url,
        })
      } else {
        util.showMsg({ msg: res.message || res.msg });
      }
    });
  },
  //下载PDF
  downloadPDF(e) {
    const _this = this;
    const { billid } = this.data;
    util.request('itf/common/hongpei/travelorder/getPdf.json', {
      billid
    }).then(res => {
      if (res.success) {
        // 显示加载提示
        wx.showLoading({ title: '下载中...' });

        // PDF 文件的远程地址（需配置合法域名）
        const fileUrl = _this.data.API_BASE_URL + util.removeLeadingSlash(res.data);

        // 下载文件到临时路径
        wx.downloadFile({
          url: fileUrl,
          success: (res) => {
            if (res.statusCode === 200) {
              // 下载成功，打开文档预览
              wx.openDocument({
                filePath: res.tempFilePath,
                showMenu: true,
                fileType: 'pdf',
                success: (res) => {
                  // 提示用户通过右上角菜单保存
                  // wx.showToast({ title: '已打开，请保存', icon: 'none' });
                },
                fail: (err) => {
                  util.showMsg({
                    msg: '打开失败',
                    icon: 'error'
                  })
                }
              });
            }
          },
          fail: (err) => {
            util.showMsg({
              msg: '下载失败',
              icon: 'error'
            })
          },
          complete: () => {
            wx.hideLoading();
          }
        });
      } else {
        util.showMsg({ msg: res.message || res.msg });
      }
    });
  },
  // 拨打客服电话
  callCustomerService: function () {
    wx.makePhoneCall({
      phoneNumber: this.data.hpXcdVOS.lxr_dh,
      success: function () {
        console.log("成功拨打电话")
      },
      fail: function (err) {
        console.log("拨打电话失败:", err)
        wx.showToast({
          title: '拨打电话失败',
          icon: 'none'
        })
      }
    })
  },
  previewImage: function (e) {
    const tps = e.currentTarget.dataset.tps; // 获取当前图片地址
    const currentUrl = e.currentTarget.dataset.src; // 获取当前图片地址
    let imgList = [];
    tps.forEach(item => {
      imgList.push(this.data.API_BASE_URL + 'itf/common/att/download.do?attrId=' + item)
    })
    wx.previewImage({
      current: currentUrl, // 当前显示图片的http链接
      urls: imgList,      // 需要预览的图片http链接列表
      success: (res) => { },
      fail: (err) => {
        console.error('预览失败', err)
      }
    })
  },
  //
  handleScroll(e) {
    const scrollTop = e.detail.scrollTop;
    const offsets = this.data.offsets;
    let dayIndex = 0;
    // 从后向前查找第一个小于等于 scrollTop 的位置
    for (let i = offsets.length - 1; i >= 0; i--) {
      if (offsets[i] <= scrollTop) {
        dayIndex = i;
        break;
      }
    }
    this.setData({ dayIndex });
  },
  // 点击按钮滚动到第5项（索引为4）
  scrollToItem(e) {
    const index = e.currentTarget.dataset.index;
    this.setData({
      dayIndex: index,
      targetId: 'item' + index // 对应 id="item4" 的元素
    });
  },
  //评价
  comment(e) {
    const { type, billid } = this.data;
    wx.navigateTo({
      url: '/pages/comment/comment?billid=' + billid + '&type=' + type,
    })
  },
  //前往资源点详情
  goZydDetail(e) {
    const zyd_pk = e.currentTarget.dataset.zyd_pk;
    wx.navigateTo({
      url: '/pages/pointDetails/pointDetails?billid=' + zyd_pk,
    })
  },
  //复制行程单号
  copyText() {
    wx.setClipboardData({
      data: this.data.hpXcdVOS.xcd_code
    });
    util.showMsg("复制成功")
  },
  //提交行程
  submit() {
    const _this = this;
    wx.showLoading({
      title: '提交行程中...',
      mask: true
    })
    util.request('/itf/common/hongpei/travelorder/submit.json', {
      billid: _this.data.billid
    }, "POST").then(res => {
      wx.hideLoading()
      if (res.success) {
        util.showMsg({
          msg: "提交行程单成功",
          icon: 'success',
          success: () => {
            wx.switchTab({
              url: '/pages/tripBill/tripBill',
            })
          }
        });
      } else {
        util.showMsg({ msg: res.message || res.msg });
      }
    });
  },
  //返回行程单
  backTrip() {
    wx.navigateBack();
  },
  //已完成
  completed() {
    const _this = this;
    const billid = this.data.billid;
    util.request('/itf/common/hongpei/travelorder/completeTravelOrderDetailList.json', {
      billid
    }, "POST").then(res => {
      if (res.success) {
        util.showMsg({
          msg: "行程已完成",
          icon: 'success',
          success: () => {
            _this.refresh();
          }
        });
      } else {
        util.showMsg({ msg: res.message || res.msg });
      }
    });
  },
  //路线调整
  luxiantiaozheng(e) {
    const billid = this.data.billid;
    const type = this.data.type;
    wx.navigateTo({
      url: '/pagesTripbill/routeCorrect/routeCorrect?billid=' + billid + '&type=' + type,
    })
  },
  //接单
  takeOrder(e) {
    const _this = this;
    const billid = this.data.billid;
    wx.showModal({
      title: '提示',
      content: '是否确认接单？',
      success(res) {
        if (res.confirm) {
          wx.showLoading({
            title: '接单中...',
            mask: true
          })
          util.request('/itf/common/hongpei/travelorder/receive.json', {
            billid
          }, "POST").then(res => {
            wx.hideLoading()
            if (res.success) {
              util.showMsg({
                msg: "接单成功",
                icon: 'success',
                success: () => {
                  _this.refresh();
                }
              });
            } else {
              util.showMsg({ msg: res.message || res.msg });
            }
          });
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
  //刷新
  refresh() {
    this.getTravelOrder();
    this.queryTravelOrderLogList();
  },
  //获取行程进度数据
  queryTravelOrderLogList() {
    const _this = this;
    util.request('/itf/common/hongpei/travelorder/queryTravelOrderLogList.json', {
      billid: _this.data.billid,
      type: _this.data.type
    }).then(res => {
      if (res.success) {
        _this.setData({
          progressList: res.data.logNode,
          recordList: res.data.hpXcdLogVO
        })
      } else {
        util.showMsg({ msg: res.message || res.msg });
      }
    });
  },
  //获取行程单预览数据
  async getTravelOrder() {
    const _this = this;
    const { billid, type } = this.data;
    return util.request('/itf/common/hongpei/travelorder/getTravelOrder.json', {
      billid,
      type
    }).then(res => {
      if (res.success) {
        let { hpXcdVOS, xcdDetail, xcdPerson, evaluateList } = res.data;
        xcdDetail.forEach(item => {
          item.tps = item.tps ? item.tps.split(",") : item.tps;
        })
        evaluateList.forEach(item => {
          item.pj_files = item.pj_files ? item.pj_files.split(",") : item.pj_files;
        })

        this.setData({
          hpXcdVOS,
          xcdDetail,
          xcdPerson,
          evaluateList
        })
      } else {
        util.showMsg({ msg: res.message || res.msg });
      }
    });
  },
  readXcdEvaluate() {
    const _this = this;
    util.request('/itf/common/hongpei/evaluate/readXcdEvaluate.json', {
      billid: _this.data.billid
    }, "POST").then(res => {
      if (res.success) {

      } else {

      }
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const { billid, type, setName } = options;
    let title = '';
    this.setData({ billid, type })
    if (setName != 2) {
      switch (Number(options.type)) {
        case 1:
          title = "路线调整";
          break;
        case 2:
          title = "确认行程";
          break;
        case 3:
          title = "班次实施";
          break;
        case 4:
          title = "我要反馈";
          break;
        case 5:
          title = "接受订单";
          break;
        case 6:
          title = "路线调整";
          break;
        case 7:
          title = "组织派单";
          break;
        case 8:
          title = "过程管理";
          break;
        case 9:
          title = "结果反馈";
          break;
      }
    }
    if (title) {
      wx.setNavigationBarTitle({
        title
      });
    }
    if (type == 9) {
      this.readXcdEvaluate()
    }
  },
  changeType(e) {
    this.setData({
      typeIndex: e.currentTarget.dataset.type
    })
  },
  // 计算所有元素的顶部位置
  calculateOffsets() {
    const query = wx.createSelectorQuery().in(this);

    query.selectAll('.planInfo').boundingClientRect(rects => {
      if (!rects || rects.length === 0) {
        console.error('未找到 .planInfo 元素');
        return;
      }

      console.log('获取到的元素信息:', rects);
      const offsets = [0];
      let totalHeight = 0;

      for (let i = 1; i < rects.length; i++) {
        totalHeight += rects[i - 1].height;
        offsets.push(totalHeight);
      }
      console.log(offsets)
      this.setData({ offsets });
    }).exec();
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  async onShow() {
    await this.getTravelOrder();
    this.queryTravelOrderLogList();
    // 等待视图层渲染完成
    wx.nextTick(() => {
      this.calculateOffsets();
    });
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})